package com.loong.coupon.handler;

import com.loong.common.utils.TransformUtils;
import com.loong.coupon.business.CouponApplyRuleBusiness;
import com.loong.coupon.common.backend.param.CouponApplyRuleParam;
import com.loong.coupon.common.backend.result.CouponApplyRuleResult;
import com.loong.coupon.mapper.CouponApplyRuleMapper;
import com.loong.coupon.mapper.CouponMapper;
import com.loong.coupon.model.CouponApplyRule;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 处理优惠券适用规则相关业务的handler
 * @Author: LiuQun
 * @Date: 2021/1/11 22:20
 */
@Service
public class CouponApplyRuleHandler {

    @Resource
    private CouponApplyRuleBusiness ruleBusiness;

    /**
     *后台新增优惠券规则
     * @param ruleParamList 优惠券规则参数集合
     */
    @Transactional
    public void saveCouponApplyRule(List<CouponApplyRuleParam> ruleParamList){
        List<CouponApplyRule> ruleList = TransformUtils.transformList(ruleParamList, CouponApplyRule.class);
        ruleBusiness.save(ruleList);
    }

    /**
     * 后台根据优惠券id查询优惠券适用规则
     * @param couponId 优惠券id
     * @return 优惠券适用规则集合
     */
    protected List<CouponApplyRuleResult> findCouponApplyRuleByCouponId(Long couponId){
        List<CouponApplyRuleResult> ruleResultList = new ArrayList<>();
        List<CouponApplyRule> ruleList = ruleBusiness.findAllBy("couponId", couponId);
        if (!CollectionUtils.isEmpty(ruleList)) ruleResultList = TransformUtils.transformList(ruleList,CouponApplyRuleResult.class);
        return ruleResultList;
    }

    /**
     * 后台更新优惠券适用规则
     * @param ruleParamList 优惠券规则参数集合
     */
    @Transactional
    public void updateCouponApplyRule(List<CouponApplyRuleParam> ruleParamList){
        Date date = new Date();
        for (CouponApplyRuleParam ruleParam : ruleParamList) {
            ruleParam.setLastUpdateTime(date);
            ruleBusiness.updateByPrimaryKeySelective(TransformUtils.transform(ruleParam,CouponApplyRule.class));
        }
    }

    /**
     * 后台删除优惠券适用规则
     * @param couponId 优惠券id
     */
    protected void deleteCouponApplyRule(Long couponId){
        ruleBusiness.deleteCouponApplyRuleByCouponId(couponId);
    }
}
